import type { ILoginState } from './index.d'
import type { ILogin } from '@/type/index.d'
import { localCache } from '@/utils/storage'
import { defineStore } from 'pinia'
import { getUserInfoByIdApi, getUserMenusByRoleIdApi, loginApi } from '../../service/login/index'
import router from '@/router/index'
import { LOGIN_TOKEN, PERMISSION, USER_INFO, USER_MENUS } from '@/global/constants'
import { mapMenuListToPermissions, mapMenusToRoutes } from '@/utils/map-menus'
import type { RouteRecordRaw } from 'vue-router'
import useMainStore from '@/stores/main/main'

export const useLoginStore = defineStore('login', {
  state: (): ILoginState => ({
    id: -1,
    token: '',
    userInfo: {},
    userMenus: [],
    permissions: localCache.getStorage(PERMISSION)
  }),
  actions: {
    async loginAction(obj: ILogin) {
      const loginRes = await loginApi(obj)

      localCache.setStorage(LOGIN_TOKEN, loginRes.data.token)

      this.id = loginRes.data.id

      // 根据角色id获取用户信息
      this.getUserInfoAction()

      // 根据角色id请求用户权限
      const userMenusRes = await getUserMenusByRoleIdApi(this.id)
      this.userMenus = userMenusRes.data
      localCache.setStorage(USER_MENUS, userMenusRes.data)

      // 获取登陆用户的所有按钮的权限
      const permissions: string[] = mapMenuListToPermissions(this.userMenus)
      this.permissions = permissions
      localCache.setStorage(PERMISSION, permissions)

      const routes: RouteRecordRaw[] = mapMenusToRoutes(userMenusRes.data)
      console.log(routes)
      routes.forEach((route) => router.addRoute('main', route))

      router.push(routes[0].path)
    },
    // 获取登陆用户权限信息
    async getUserInfoAction() {
      const userInfoRes = await getUserInfoByIdApi(this.id)

      this.userInfo = userInfoRes.data
      localCache.setStorage(USER_INFO, userInfoRes.data)
    },

    // 初始化用户数据（token、userInfo、userMenus）
    loadLocalCacheAction() {
      const token = localCache.getStorage(LOGIN_TOKEN)
      const userInfo = localCache.getStorage(USER_INFO)
      const userMenus = localCache.getStorage(USER_MENUS)

      if (token && userInfo && userMenus) {
        this.token = token
        this.userInfo = userInfo
        this.userMenus = userMenus

        // 执行动态路由注册
        const routes: RouteRecordRaw[] = mapMenusToRoutes(userMenus)
        routes.forEach((route) => router.addRoute('main', route))
      }

      //   获取所有用户和部门信息
      // const mainStore = useMainStore()
      // mainStore.fetchEntireDataAction()
    }
  }
})
